<template>
  <div class="ztrust-score-container">
    <!-- 筛选控制区域 -->
    <div class="filter-controls">
      <a-card title="筛选条件" :bordered="false" class="filter-card">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="Cybertwin ID">
              <a-input
                v-model:value="filters.cybertwinId"
                placeholder="请输入 Cybertwin ID"
                allow-clear
                @change="applyFilters"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="基础分数范围">
              <a-slider
                v-model:value="filters.basicScoreRange"
                range
                :min="0"
                :max="100"
                @change="applyFilters"
              />
              <div class="score-range-text">
                {{ filters.basicScoreRange[0] }} - {{ filters.basicScoreRange[1] }}
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="动态分数范围">
              <a-slider
                v-model:value="filters.dynamicScoreRange"
                range
                :min="0"
                :max="100"
                @change="applyFilters"
              />
              <div class="score-range-text">
                {{ filters.dynamicScoreRange[0] }} - {{ filters.dynamicScoreRange[1] }}
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="排序方式">
              <a-select
                v-model:value="sortConfig.key"
                @change="applySorting"
                placeholder="选择排序字段"
              >
                <a-select-option value="cybertwin_id">Cybertwin ID</a-select-option>
                <a-select-option value="basic_score">基础分数</a-select-option>
                <a-select-option value="dynamic_score">动态分数</a-select-option>
              </a-select>
              <a-radio-group
                v-model:value="sortConfig.order"
                @change="applySorting"
                style="margin-top: 8px"
              >
                <a-radio-button value="asc">升序</a-radio-button>
                <a-radio-button value="desc">降序</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-statistic
            title="总记录数"
            :value="filteredData.length"
            class="stat-card"
          />
        </a-col>
        <a-col :span="8">
          <a-statistic
            title="平均基础分数"
            :value="averageBasicScore"
            :precision="2"
            class="stat-card"
          />
        </a-col>
        <a-col :span="8">
          <a-statistic
            title="平均动态分数"
            :value="averageDynamicScore"
            :precision="2"
            class="stat-card"
          />
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="sortedData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="cybertwin_id"
        size="middle"
      >
        <template #headerCell="{ column }">
          <template v-if="column.dataIndex === 'trust_level'">
            <div class="table-header-with-tooltip">
              <span>信任等级</span>
              <a-tooltip title="信任等级使用基础分数计算，它会影响动态分数的恢复速度">
                <info-circle-outlined style="color: #999;" />
              </a-tooltip>
            </div>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'cybertwin_id'">
            <a-tag color="blue">{{ record.cybertwin_id }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'basic_score'">
            <div class="score-cell">
              <a-progress
                :percent="record.basic_score"
                :stroke-color="getScoreColor(record.basic_score)"
                size="small"
                :show-info="false"
              />
              <span class="score-text">{{ record.basic_score.toFixed(2) }}</span>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'dynamic_score'">
            <div class="score-cell">
              <a-progress
                :percent="record.dynamic_score"
                :stroke-color="getScoreColor(record.dynamic_score)"
                size="small"
                :show-info="false"
              />
              <span class="score-text">{{ record.dynamic_score.toFixed(2) }}</span>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'trust_level'">
            <a-tag :color="getTrustLevelColor(record.basic_score, record.dynamic_score)">
              {{ getTrustLevel(record.basic_score, record.dynamic_score) }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'actions'">
            <a-space>
              <a-button
                type="link"
                @click="viewDetails(record)"
                size="small"
              >
                查看详情
              </a-button>
              <a-button
                type="link"
                @click="viewEvents(record.cybertwin_id)"
                size="small"
              >
                查看事件
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="信任评级详情"
      :footer="null"
      width="600px"
    >
      <div v-if="selectedRecord">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="Cybertwin ID">
            <a-tag color="blue">{{ selectedRecord.cybertwin_id }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item>
            <template #label>
              <div class="table-header-with-tooltip">
                <span>信任等级</span>
                <a-tooltip title="信任等级使用基础分数计算">
                  <info-circle-outlined style="color: #999;" />
                </a-tooltip>
              </div>
            </template>
            <a-tag :color="getTrustLevelColor(selectedRecord.basic_score, selectedRecord.dynamic_score)">
              {{ getTrustLevel(selectedRecord.basic_score, selectedRecord.dynamic_score) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="基础分数">
            <div class="detail-score">
              <a-progress
                :percent="selectedRecord.basic_score"
                :stroke-color="getScoreColor(selectedRecord.basic_score)"
                size="small"
              />
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="动态分数">
            <div class="detail-score">
              <a-progress
                :percent="selectedRecord.dynamic_score"
                :stroke-color="getScoreColor(selectedRecord.dynamic_score)"
                size="small"
              />
            </div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 事件抽屉 -->
    <a-drawer
      v-model:open="eventsDrawerVisible"
      :title="`Cybertwin ${currentCybertwinId} 的信任事件`"
      placement="right"
      width="900"
      class="events-drawer"
    >
      <div v-if="eventsLoading" class="loading-container">
        <a-spin size="large" />
        <div class="loading-text">正在加载事件数据...</div>
      </div>
      
      <div v-else-if="eventsList.length === 0" class="empty-container">
        <a-empty description="暂无事件数据" />
      </div>
      
      <div v-else class="events-content">
        <!-- 事件统计 -->
        <div class="events-stats">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-statistic
                title="总事件数"
                :value="eventsList.length"
                class="stat-card"
              />
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="信任提升事件"
                :value="eventsList.filter(e => e.event === 'INCREASE').length"
                class="stat-card stat-increase"
              />
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="信任降低事件"
                :value="eventsList.filter(e => e.event === 'REDUCE').length"
                class="stat-card stat-reduce"
              />
            </a-col>
          </a-row>
        </div>

        <!-- 事件列表 -->
        <div class="events-list">
          <a-timeline>
            <a-timeline-item
              v-for="event in eventsList"
              :key="event.id"
              :color="event.event === 'INCREASE' ? 'green' : 'red'"
            >
              <template #dot>
                <div :class="`event-dot ${event.event === 'INCREASE' ? 'increase' : 'reduce'}`">
                  {{ event.event === 'INCREASE' ? '↑' : '↓' }}
                </div>
              </template>
              
              <div class="event-item" :class="{ 'event-increase': event.event === 'INCREASE', 'event-reduce': event.event === 'REDUCE' }">
                <div class="event-header">
                  <a-tag
                    :color="event.event === 'INCREASE' ? 'green' : 'red'"
                    class="event-type-tag"
                  >
                    {{ event.event === 'INCREASE' ? '信任提升' : '信任降低' }}
                  </a-tag>
                  <span class="event-time">
                    {{ new Date(event.trigger_at).toLocaleString('zh-CN') }}
                  </span>
                </div>
                
                <div class="event-content">
                  <div class="event-description">
                    <strong>事件描述：</strong>{{ event.event_desc }}
                  </div>
                  <div class="score-change">
                    <strong>分数变化：</strong>{{ event.score_desc }}
                  </div>
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { GetAllZtrustScores, GetZtrustEventsByCybertwinId, type ZtrustScore, type ZtrustEvent } from '@/api/ztrust'
import type { TableColumnsType } from 'ant-design-vue'
import { InfoCircleOutlined } from '@ant-design/icons-vue'

// 响应式数据
const loading = ref(false)
const rawData = ref<ZtrustScore[]>([])
const detailModalVisible = ref(false)
const selectedRecord = ref<ZtrustScore | null>(null)

// 事件抽屉相关数据
const eventsDrawerVisible = ref(false)
const eventsLoading = ref(false)
const eventsList = ref<ZtrustEvent[]>([])
const currentCybertwinId = ref<number | null>(null)

// 筛选条件
const filters = reactive({
  cybertwinId: '',
  basicScoreRange: [0, 100] as [number, number],
  dynamicScoreRange: [0, 100] as [number, number]
})

// 排序配置
const sortConfig = reactive({
  key: 'basic_score' as keyof ZtrustScore,
  order: 'desc' as 'asc' | 'desc'
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列定义
const columns: TableColumnsType<ZtrustScore> = [
  {
    title: 'Cybertwin ID',
    dataIndex: 'cybertwin_id',
    key: 'cybertwin_id',
    width: 150,
    sorter: true
  },
  {
    title: '基础分数',
    dataIndex: 'basic_score',
    key: 'basic_score',
    width: 200,
    sorter: true
  },
  {
    title: '动态分数',
    dataIndex: 'dynamic_score',
    key: 'dynamic_score',
    width: 200,
    sorter: true
  },
  {
    title: '信任等级',
    dataIndex: 'trust_level',
    key: 'trust_level',
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'actions',
    key: 'actions',
    width: 150
  }
]

// 计算属性 - 直接使用原始数据，不添加总分
const processedData = computed(() => {
  return rawData.value
})

// 筛选后的数据
const filteredData = computed(() => {
  return processedData.value.filter(item => {
    // Cybertwin ID 筛选
    if (filters.cybertwinId && !item.cybertwin_id.toString().includes(filters.cybertwinId)) {
      return false
    }
    
    // 基础分数范围筛选
    if (item.basic_score < filters.basicScoreRange[0] || item.basic_score > filters.basicScoreRange[1]) {
      return false
    }
    
    // 动态分数范围筛选
    if (item.dynamic_score < filters.dynamicScoreRange[0] || item.dynamic_score > filters.dynamicScoreRange[1]) {
      return false
    }
    
    return true
  })
})

// 排序后的数据
const sortedData = computed(() => {
  const data = [...filteredData.value]
  
  if (sortConfig.key) {
    data.sort((a, b) => {
      const aVal = a[sortConfig.key as keyof ZtrustScore] as number
      const bVal = b[sortConfig.key as keyof ZtrustScore] as number
      
      if (sortConfig.order === 'asc') {
        return aVal - bVal
      } else {
        return bVal - aVal
      }
    })
  }
  
  return data
})

// 统计信息计算
const averageBasicScore = computed(() => {
  if (filteredData.value.length === 0) return 0
  const sum = filteredData.value.reduce((acc, item) => acc + item.basic_score, 0)
  return sum / filteredData.value.length
})

const averageDynamicScore = computed(() => {
  if (filteredData.value.length === 0) return 0
  const sum = filteredData.value.reduce((acc, item) => acc + item.dynamic_score, 0)
  return sum / filteredData.value.length
})

// 方法
const fetchData = async () => {
  loading.value = true
  try {
    const res = await GetAllZtrustScores()
    console.log('获取信任评级数据:', res)
    if (res.code === 0) {
      rawData.value = res.data || []
    }
  } catch (error) {
    console.error('获取信任评级数据失败:', error)
  } finally {
    loading.value = false
  }
}

const applyFilters = () => {
  pagination.current = 1
}

const applySorting = () => {
  // 排序逻辑已在 computed 中处理
}

const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  
  if (sorter.field) {
    sortConfig.key = sorter.field
    sortConfig.order = sorter.order === 'ascend' ? 'asc' : 'desc'
  }
}

const getScoreColor = (score: number) => {
  if (score <= 60) {
    return '#f5222d' // 红色
  } else if (score <= 80) {
    return '#faad14' // 橙色
  } else {
    return '#52c41a' // 绿色
  }
}

const getTrustLevelColor = (basicScore: number, dynamicScore: number) => {
//   const avgScore = (basicScore + dynamicScore) / 2
  const evaScore = basicScore
  if (evaScore <= 60) {
    return 'red'
  } else if (evaScore <= 80) {
    return 'orange'
  } else {
    return 'green'
  }
}

const getTrustLevel = (basicScore: number, dynamicScore: number) => {
//   const avgScore = (basicScore + dynamicScore) / 2
  const evaScore = basicScore
  if (evaScore <= 60) {
    return '低'
  } else if (evaScore <= 80) {
    return '中'
  } else {
    return '高'
  }
}

const viewDetails = (record: ZtrustScore) => {
  selectedRecord.value = record
  detailModalVisible.value = true
}

const viewEvents = async (cybertwinId: number) => {
  currentCybertwinId.value = cybertwinId
  eventsDrawerVisible.value = true
  eventsLoading.value = true
  
  try {
    const res = await GetZtrustEventsByCybertwinId(cybertwinId)
    console.log(`获取Cybertwin ${cybertwinId} 的事件数据:`, res)
    if (res.code === 0) {
      eventsList.value = res.data || []
    } else {
      eventsList.value = []
      console.error('获取事件数据失败:', res.message)
    }
  } catch (error) {
    console.error('获取事件数据失败:', error)
    eventsList.value = []
  } finally {
    eventsLoading.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.ztrust-score-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.filter-controls {
  margin-bottom: 24px;
}

.filter-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.score-range-text {
  text-align: center;
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.score-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.score-text {
  font-weight: 600;
  min-width: 30px;
  white-space: nowrap;
}

.detail-score {
  margin: 8px 0;
}

/* 进度条样式优化 */
:deep(.ant-progress-line) {
  margin-bottom: 0;
}

:deep(.ant-progress-bg) {
  height: 8px !important;
}

/* 表格行悬停效果 */
:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5 !important;
}

/* 统计卡片样式 */
:deep(.ant-statistic-title) {
  color: #666;
  font-size: 14px;
}

:deep(.ant-statistic-content) {
  color: #1890ff;
  font-weight: 600;
}

/* 标签样式 */
:deep(.ant-tag) {
  margin: 0;
  border-radius: 4px;
}

/* 滑块样式 */
:deep(.ant-slider) {
  margin: 8px 0;
}

/* 表单项间距调整 */
:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}

/* 按钮组样式 */
:deep(.ant-radio-group) {
  display: flex;
  width: 100%;
}

:deep(.ant-radio-button-wrapper) {
  flex: 1;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .ztrust-score-container {
    padding: 16px;
  }
  
  .filter-controls .ant-col {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .score-cell {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .stats-section .ant-col {
    margin-bottom: 16px;
  }
}

/* 提示图标样式 */
:deep(.anticon-info-circle) {
  font-size: 12px;
  opacity: 0.6;
  transition: all 0.2s ease;
}

:deep(.anticon-info-circle:hover) {
  opacity: 1;
  color: #1890ff !important;
  transform: scale(1.1);
}

/* 表头提示样式 */
.table-header-with-tooltip {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 事件抽屉样式 */
.events-drawer :deep(.ant-drawer-body) {
  padding: 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.loading-text {
  margin-top: 16px;
  color: #666;
}

.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.events-content {
  padding: 24px;
}

.events-stats {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.events-stats .stat-card {
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.stat-increase :deep(.ant-statistic-content) {
  color: #52c41a !important;
}

.stat-reduce :deep(.ant-statistic-content) {
  color: #f5222d !important;
}

.events-list {
  max-height: calc(100vh - 300px);
  overflow-y: auto;
  padding-left: 8px;
  padding-right: 16px;
}

.event-dot {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 16px;
  position: relative;
  z-index: 20;
  border: 3px solid white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.event-dot.increase {
  background-color: #52c41a;
}

.event-dot.reduce {
  background-color: #f5222d;
}

.event-item {
  padding: 16px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 12px;
  margin-left: 8px;
  border-left: 3px solid transparent;
  transition: all 0.2s ease;
}

.event-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  transform: translateY(-1px);
}

.event-item.event-increase {
  border-left-color: #52c41a;
}

.event-item.event-reduce {
  border-left-color: #f5222d;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.event-type-tag {
  font-weight: 500;
}

.event-time {
  color: #666;
  font-size: 12px;
}

.event-content {
  color: #333;
}

.event-description,
.score-change {
  margin-bottom: 8px;
  line-height: 1.6;
}

.event-description:last-child,
.score-change:last-child {
  margin-bottom: 0;
}

/* 时间轴样式优化 */
:deep(.ant-timeline) {
  padding-left: 8px;
}

:deep(.ant-timeline-item-content) {
  margin-left: 36px;
  min-height: auto;
}

:deep(.ant-timeline-item-tail) {
  border-left: 2px solid #e8e8e8;
  left: 14px;
  z-index: 1;
}

:deep(.ant-timeline-item-head) {
  position: relative;
  z-index: 10;
  left: 0;
}

/* 确保事件点在最上层 */
:deep(.ant-timeline .ant-timeline-item-head-custom) {
  position: relative;
  z-index: 15;
  background: white;
  border-radius: 50%;
  padding: 2px;
  left: 0;
}
</style>